package com.zxs.user.controller;

import com.zxs.user.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import parm.AddressListParam;
import parm.AddressRemoveParam;
import parm.AdressParm;
import pojo.Address;
import utils.R;

/**
 * @author zxs
 * *7 11:40
 */
@RestController
@RequestMapping("/user/address")
public class AdressController {

    @Autowired
    private AddressService addressService;

    /**
     * 根据用户id查询用户地址
     * @param param
     * @param result
     * @return
     */
    @PostMapping("list")
    public R listAdresses(@RequestBody @Validated AddressListParam param, BindingResult result){
        if (result.hasErrors()){
            return  R.fail("参数异常，重新输入！");
        }
        return  addressService.listAdresses(param.getUserId());
    }

    /**
     * 添加地址
     * @param addressParm
     * @param result
     * @return
     */
    @PostMapping("save")
    public R save(@RequestBody @Validated AdressParm addressParm, BindingResult result){
        if (result.hasErrors()){
            return R.fail("参数异常，请重新输入！");
        }
        // 完善前端请求
        Address adress =addressParm.getAdd();
        adress.setUserId(addressParm.getUserId());
        return addressService.save(adress);
    }
    @PostMapping("remove")
    public R remove(@RequestBody @Validated AddressRemoveParam removeParam, BindingResult result){
        if (result.hasErrors()){
            return  R.fail("参数异常，删除失败");
        }
        return  addressService.remove(removeParam.getId());
    }
}
